import { useEffect, useImperativeHandle } from 'react';
import { Modal, Form, Tree } from 'antd';
import { useState } from 'react';
import { IAction, IModalProps } from '@/types/modal';
import { Role, Menu } from '@/types';
import { getMenuList, updatePermission } from '@/api';
import { message } from '@/utils/AntdGlobal';

export default function SetPermission(props: IModalProps<Role.RoleItem>) {
  const [visiable, setVisiable] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState<string[]>();
  const [menuList, setMenuList] = useState<Menu.MenuItem[]>([]);
  const [roleInfo, setRoleInfo] = useState<Role.RoleItem>();
  const [permission, setPermission] = useState<Role.Permission>();

  useEffect(() => {
    getMenuData();
  }, []);
  const getMenuData = async () => {
    const menuList = await getMenuList();
    setMenuList(menuList);
  };
  const handleSubmit = async () => {
    if (permission) {
      await updatePermission(permission);
      message.success('权限设置成功');
      handleCancel();
      props.update();
    }
  };
  const handleCancel = () => {
    setVisiable(false);
    setPermission(undefined);
  };
  useImperativeHandle(props.mRef, () => ({
    open
  }));

  const open = (type: IAction, data?: Role.RoleItem) => {
    setVisiable(true);
    if (data) {
      setRoleInfo(data);
      setCheckedKeys(data.permissionList.checkedKeys);
    }
  };

  const onCheck = (checkedKeysValue: any, item: any) => {
    setCheckedKeys(checkedKeysValue);
    const checkedKeys: string[] = [];
    const parentKeys: string[] = [];
    item.checkedNodes.map((node: Menu.MenuItem) => {
      if (node.menuType === 2) {
        checkedKeys.push(node._id); // button
      } else {
        parentKeys.push(node._id);
      }
    });
    setPermission({
      _id: roleInfo?._id || '',
      permissionList: {
        checkedKeys,
        halfCheckedKeys: parentKeys.concat(item.halfCheckedKeys)
      }
    });
  };

  return (
    <Modal
      title='设置权限'
      width={800}
      open={visiable}
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <Form labelCol={{ span: 4 }} labelAlign='right'>
        <Form.Item label='角色名称'>
          <span>{roleInfo?.roleName}</span>
        </Form.Item>
        <Form.Item label='权限'>
          <Tree
            checkable
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            treeData={menuList}
            defaultExpandAll
            fieldNames={{
              title: 'menuName',
              key: '_id',
              children: 'children'
            }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}
